/*
 * socket-servidor.cpp
 *
 *  Created on: 03/10/2011
 *      Author: guido
 */

#include "socket-servidor.h"
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <cstring>

SocketServidor::SocketServidor(unsigned short int puerto) {
	struct sockaddr_in serv_addr;
	// Creo el socket
	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		perror("creando socket");
		std::cout << strerror(errno);
		exit(1);
	}

	// Lleno de ceros la estructura
	memset((char *) &serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET; // Tipo internet
	serv_addr.sin_port = htons(puerto);
	serv_addr.sin_addr.s_addr = INADDR_ANY;

	int RAval=1;
	setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&RAval,sizeof(RAval));

	// Enlazo la dirección al socket
	if (bind(sockfd, (struct sockaddr *) &serv_addr,
			(socklen_t) sizeof(struct sockaddr)) < 0) {
		perror("bind");
		printf("%sn", strerror(errno));
		exit(1);
	}

	listen(sockfd, 5);
}

int SocketServidor::aceptar() {
	struct sockaddr_in cli_addr;
	unsigned int clilen = (socklen_t) sizeof(cli_addr);
	int newsockfd = accept(this->sockfd, (struct sockaddr *) &cli_addr,
			&clilen);
	return newsockfd;
}

